// pages/reservation/add/add.js
const regeneratorRuntime = require('../../../lib/regenerator-runtime.js')
const util = require('../../../utils/util.js')
const networkUtil = require('../../../utils/networkutil.js')
const networkUtilV2 = require('../../../utils/networkUtilV2.js')

const app = getApp()
let logStrPrefix = "reservation.add"

Page({
	
	/**
	 * 页面的初始数据
	 */
	data: {
		/**
		 * 相关变量定义
		 */
		//预约单号
		reservationno: null,
		//预约单号》二维码base64格式的字符串
		qrcode_base64_data: null,
		
		//二维码对话框状态
		showDialog_reservno: false,
		
		//接待部门
		deptno: null,
		deptname: null,
		//提示列表
		hideScroll_dept: true,
		scrollHeight_dept: 0,
		depts: [],
		
		//接待人
		employeenoReception: null,
		employeenameReception: null,
		hideScroll_employee: true,
		scrollHeight_employee: 0,
		employees: [],
		
		//手机号
		employeenoPhone: null,
		
		//来访日期
		forecastVisitingTime: null,
		forecastDepartureTime: null,
		
		//受访区域
		districtno: null,
		districtName: null,
		showDialog_district: false,
		districts: [],
		
		//访客单位
		visitorCompany: null,
		visitingMatters: null,
		//来访事宜》textarea状态
		visitMatterStatus: false,
		
		//访客信息
		visitors: [],
		showDialog_visitor: false,
		mVisitor: null,
		mIdcardno: null,
		mPhone: null,
		mVisitorposition: null,
		mCarryitems: null,
		//访客照片
		mPhotoUrl: null,
		
		/**
		 * 请求频率限制相关变量。
		 */
		//上次请求的时间,单位为毫秒
		lastInvokeMillisecond: null,
		//上次设置的定时器的编号
		lastTimeoutId: null,
		
		
	},
	
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		
		/**
		 * 1、获取生成的预约单号，二维码base64格式的字符串。
		 */
		let that = this
		that.getReservationno()
		
		/**
		 * 2、获取受访区域信息
		 */
		that.getDistricts()
		
		
	},
	
	/**
	 * 获取生成的预约单号，二维码base64格式的字符串。
	 */
	getReservationno: function (res) {
		//获取生成的预约单号
		let that = this
		let url = app.globalData.baseUrl + "/reservation/getNewReservationNo"
		let requestData = {}
		
		return networkUtil.request_post(url, requestData).then((res) => {
			console.info("reservation.add.getReservationno() 获取预约单号，已完成..")
			//util.prettyPrint("reservationno",res.data)
			
			that.setData({
				reservationno: res.data.reservationno,
				qrcode_base64_data: res.data.qrCodeBase64Data
			})
			return app.globalData.SUCCESS_STR
		}).catch((res) => {
			console.error("reservation.add.getReservationno() 获取预约单号，发生错误!", res)
			return app.globalData.ERROR_STR
		})
	},
	
	/**
	 * 获取受访区域列表
	 */
	getDistricts: function () {
		//获取受访区域列表
		let that = this
		let url = app.globalData.baseUrl + "/district/getDistricts"
		let requestData = {
			companyno: app.globalData.wxUser.companyno
		}
		
		networkUtil.request_post(url, requestData).then((res) => {
			//若已获取受访区域信息
			console.log(logStrPrefix + ".getDistricts() 获取受访区域信息，已完成..")
			//util.prettyPrint("districts",res.data)
			
			that.setData({
				districts: res.data
			})
		}).catch((res)=>{
			//若未获取受访区域信息
			console.error(logStrPrefix+".getDistricts() 获取受访区域信息，发生错误!", res)
		})
	},
	
	/**
	 * 绑定文本框的输入事件，获取用户输入的信息，并存入对应的变量中。
	 */
	bindInput_common: function (event) {
		let that = this
		let tagId = event.currentTarget.dataset.name
		let tagValue = event.detail.value
		
		that.setData({
			[tagId]: tagValue
		})
	},
	
	/**
	 * 根据输入关键词产生"提示列表"。
	 */
	bindInput_hint: function (event) {
		let that = this
		let tagId = event.currentTarget.dataset.name
		let tagValue = event.detail.value
		
		/**
		 * 请求频率限制。
		 */
		let isInvoke = that.isBeyondLimitInterval()
		//若本次请求被限制，则延迟执行该请求。
		if (isInvoke == false) {
			//取消上次设置的定时器
			let lastTimeoutId = that.data.lastTimeoutId
			if (lastTimeoutId != null) {
				clearTimeout(lastTimeoutId)
			}
			//设置本次定时器
			let timeoutFunc = (event) => {
				that.bindInput_hint(event)
			}
			let timeoutId = setTimeout(timeoutFunc, 1000, event)
			that.setData({
				lastTimeoutId: timeoutId
			})
			return
		}
		
		/**
		 * 根据输入关键词产生"提示列表"。
		 */
		switch (tagId) {
			
			//查询接待部门
			case "deptname": {
				//若tagValue不含有信息,清空提示列表
				if (util.isEmpty(tagValue)) {
					//清空提示列表
					that.setData({
						depts: [],
						hideScroll_dept: true,
						scrollHeight_dept: 0
					})
					return
				}
				//若tagValue含有信息
				let url = app.globalData.baseUrl + "/dept/getDeptByNameDim"
				let requestData = {
					deptname: tagValue,
					companyno: app.globalData.wxUser.companyno
				}
				networkUtil.request_post(url, requestData, false).then((res) => {
					//若已获取部门信息
					console.log(logStrPrefix + " 获取部门信息，已完成..")
					//util.prettyPrint("depts",res.data)
					
					/**
					 * 分析是否取到相关信息
					 */
					if (res.data != null && res.data.length > 0) {
						//若取到相关信息
						that.setData({
							depts: res.data,
							hideScroll_dept: false,
							scrollHeight_dept: res.data.length * 71
						})
					} else {
						//若未取到相关信息
						that.setData({
							depts: [],
							hideScroll_dept: true,
							scrollHeight_dept: 0
						})
					}
				}).catch((res) => {
					//若未获取部门信息
					console.error(logStrPrefix + " 获取部门信息，发生错误!", res)
					util.showToast("获取部门信息，发生错误!")
				})
				break
			}
			
			//查询接待人
			case "employeenameReception": {
				//若tagValue不含有信息,清空提示列表
				if (util.isEmpty(tagValue)) {
					//清空提示列表
					that.setData({
						employees: [],
						hideScroll_employee: true,
						scrollHeight_employee: 0
					})
					return
				}
				//若tagValue含有信息
				let url = app.globalData.baseUrl + "/employee/getEmployeeByNameDim"
				let requestData = {
					employeename: tagValue,
					companyno: app.globalData.wxUser.companyno
				}
				networkUtil.request_post(url, requestData, false).then((res) => {
					//若已获取到接待人信息
					console.log(logStrPrefix + " 获取接待人信息，已完成..")
					//util.prettyPrint("employees",res.data)
					
					/**
					 * 分析是否取到相关信息
					 */
					if (res.data != null && res.data.length > 0) {
						//若取到相关信息
						that.setData({
							employees: res.data,
							hideScroll_employee: false,
							scrollHeight_employee: res.data.length * 71
						})
					} else {
						//若未取到相关信息
						that.setData({
							employees: [],
							hideScroll_employee: true,
							scrollHeight_employee: 0
						})
					}
				}).catch((res) => {
					//若未获取到接待人信息
					console.error(logStrPrefix + " 获取接待人信息，发生错误!", res)
					util.showToast("获取接待人信息，发生错误!")
				})
				break
			}
			
		}
	},
	
	/**
	 * 选取"提示列表"中的某一项信息
	 */
	itemSelect_hint: function (event) {
		//console.log("reservation.add 执行了itemSelect_hint()方法..")
		
		let that = this
		let tagId = event.currentTarget.dataset.name
		let tagValue = event.currentTarget.dataset.value
		
		switch (tagId) {
			
			//选择接待部门
			case "deptname": {
				//获取选择的接待部门
				that.setData({
					//接待部门
					deptno: tagValue.deptno,
					deptname: tagValue.deptname,
					//提示列表
					hideScroll_dept: true,
					scrollHeight_dept: 0,
					depts: []
				})
				break
			}
			
			//选择接待人
			case "employeenameReception": {
				//获取选择的接待人
				that.setData({
					//接待人
					employeenoReception: tagValue.employeeno,
					employeenameReception: tagValue.employeename,
					//提示列表
					hideScroll_employee: true,
					scrollHeight_employee: 0,
					employees: []
				})
				break
			}
			
			
		}
		
	},
	
	/**
	 * 获取选择的日期
	 */
	bindDateChange: function (event) {
		//console.log("reservation.add.bindDateChange()..")
		let tagId = event.currentTarget.dataset.name
		let tagValue = event.detail.value
		
		switch (tagId) {
			
			//来访日期
			case "forecastVisitingTime": {
				this.setData({
					forecastVisitingTime: tagValue,
					forecastDepartureTime: util.addDay_toDate(new Date(tagValue), 6)
				})
				break
			}
			
			//出园日期
			case "forecastDepartureTime": {
				this.setData({
					forecastDepartureTime: tagValue
				})
				break
			}
		}
	},
	
	/**
	 * 打开受访区域选择框。
	 */
	openDialog_district: function () {
		this.setData({
			showDialog_district: true
		})
	},
	
	/**
	 * 关闭受访区域选择框。
	 */
	closeDialog_district: function () {
		this.setData({
			showDialog_district: false
		})
		//根据districts中选中项，给districtno,districtName赋值
		let districts = this.data.districts
		let districtno = []
		let districtName = []
		
		for (let i = 0; i < districts.length; i++) {
			//若districts[i].checked为true
			if (districts[i].checked) {
				districtno.push(districts[i].districtno)
				districtName.push(districts[i].districtName)
			}
		}
		districtno = districtno.join(",")
		districtName = districtName.join(",")
		this.setData({
			districtno: districtno,
			districtName: districtName
		})
	},
	
	/**
	 * 选择受访区域。
	 */
	checkboxChange_district: function (event) {
		//console.log("reservation.add.checkboxChange_district()", event);
		let districts = this.data.districts
		let selectValues = event.detail.value
		
		for (let i = 0; i < districts.length; i++) {
			let district = districts[i]
			let districtno = district.districtno
			//默认将district.checked置为false
			district.checked = false
			
			//若用户选择了该选项
			for (let j = 0; j < selectValues.length; j++) {
				if (districtno == selectValues[j]) {
					district.checked = true
					break
				}
			}
		}
		
		this.setData({
			districts: districts
		})
	},
	
	/**
	 * 打开新增访客对话框。
	 */
	openDialog_visitor: function () {
		this.setData({
			showDialog_visitor: true,
			//将新增访客相关变量置为null
			mVisitor: null,
			mIdcardno: null,
			mPhone: null,
			mVisitorposition: null,
			mCarryitems: null
		})
	},
	
	/**
	 * 取消 新增访客。
	 */
	cancelDialog_visitor: function () {
		this.setData({
			showDialog_visitor: false
		})
	},
	
	/**
	 * 确认 新增访客信息。
	 */
	confirmDialog_visitor: function () {
		
		let mVisitor = this.data.mVisitor
		let mIdcardno = this.data.mIdcardno
		let mPhone = this.data.mPhone
		let mVisitorposition = this.data.mVisitorposition
		let mCarryitems = this.data.mCarryitems
		
		//分析访客信息是否完整
		if (util.isEmpty(mVisitor) || util.isEmpty(mIdcardno) || util.isEmpty(mPhone) ||
			util.isEmpty(mVisitorposition) || util.isEmpty(mCarryitems)) {
			wx.showToast({
				title: '请填写完整的访客信息!',
				icon: 'none',
				duration: 2000
			})
			return
		}
		
		/**
		 * 分析身份证号是否重复填写
		 */
		let visitors = this.data.visitors
		if (visitors.length > 0) {
			for (let i = 0; i < visitors.length; i++) {
				if (visitors[i].mIdcardno == mIdcardno.trim()) {
					util.showToast("身份证号重复,您已添加过其对应的访客信息!")
					return
				}
			}
		}
		
		//若信息完整，则存入新增的访客信息
		let visitorInfo = {
			mVisitor: mVisitor.trim(),
			mIdcardno: mIdcardno.trim(),
			mPhone: mPhone.trim(),
			mVisitorposition: mVisitorposition.trim(),
			mCarryitems: mCarryitems.trim()
		}
		visitors.push(visitorInfo)
		
		this.setData({
			visitors: visitors,
			//关闭新增访客对话框
			showDialog_visitor: false
		})
	},
	
	/**
	 * 获取用户选择的图片，将图片url存入对应的visitor中。
	 * 传入参数：visitor_idcardno
	 */
	getVisitorPic: function (event) {
		let that = this
		let visitorIdcardno = event.currentTarget.dataset.visitor_idcardno
		
		//获取用户选择的图片
		wx.chooseImage({
			count: 1, // 默认9
			sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
			success: function (res) {
				console.info("reservation.add.getVisitorPic() 获取图片,已完成..")
				let visitorPicUrl = res.tempFilePaths[0]
				let visitors = that.data.visitors
				
				for (let i = 0; i < visitors.length; i++) {
					if (visitors[i].mIdcardno == visitorIdcardno) {
						visitors[i].mPhotoUrl = visitorPicUrl
						break
					}
				}
				
				that.setData({
					visitors: visitors
				})
			}
		})
	},
	
	/**
	 * 根据图片的本地地址（photoUrl）获取其对应的base64格式的字符串。
	 */
	getPhotoBase64: function (photoUrl) {
		/**
		 * 根据图片的本地地址（photoUrl）获取其对应的base64格式的字符串。
		 */
		if (util.isEmpty(photoUrl)) {
			return null
		}
		
		let base64Str = wx.getFileSystemManager().readFileSync(photoUrl, "base64")
		return base64Str
	},
	
	/**
	 * 根据图片文件类型，生成对应的base64前缀字符串。
	 */
	getPicBase64Prefix: function (suffix) {
		let base64Prefix = null
		switch (suffix) {
			case "jpg": {
				base64Prefix = "data:image/jpeg;base64,"
				break
			}
			case "png": {
				base64Prefix = "data:image/png;base64,"
				break
			}
			default: {
				base64Prefix = "data:image/jpeg;base64,"
				break
			}
		}
		return base64Prefix
	},
	
	/**
	 * 删除访客人员信息。
	 * 传入参数: visitor_idcardno
	 */
	delVisitor: function (event) {
		let that = this
		let visitorIdcardno = event.currentTarget.dataset.visitor_idcardno
		let visitors = that.data.visitors
		
		for (let i = 0; i < visitors.length; i++) {
			if (visitors[i].mIdcardno == visitorIdcardno) {
				visitors.splice(i, 1)
				i--
				break
			}
		}
		that.setData({
			visitors: visitors
		})
	},
	
	/**
	 * 打开"预约单号二维码对话框"。
	 */
	openDialog_reservno: function () {
		let that = this
		
		that.setData({
			showDialog_reservno: true
		})
	},
	
	/**
	 * 关闭"预约单号二维码对话框"。
	 */
	cancelDialog_reservno: function () {
		this.setData({
			showDialog_reservno: false
		})
	},
	
	/**
	 * 刷新"预约单号二维码"。
	 */
	refreshQrCode_reservno: function () {
		//获取生成的预约单号，二维码base64格式的字符串。
		let that = this
		that.getReservationno()
	},
	
	/**
	 * 提交预约信息。
	 */
	submitReservation: function (event) {
		console.info("reservation.add.submitReservation()..")
		
		/**
		 * 1、检查用户填写的信息是否完整
		 */
		let that = this
		if (util.isEmpty(that.data.reservationno)) {
			util.showToast('请求错误,预约单号不可为空!')
			return
		}
		if (util.isEmpty(that.data.deptno)) {
			util.showToast('请求错误,接待部门不可为空!')
			return
		}
		if (util.isEmpty(that.data.employeenoReception)) {
			util.showToast('请求错误,接待人不可为空!')
			return
		}
		if (util.isEmpty(that.data.employeenoPhone)) {
			util.showToast('请求错误,手机号不可为空!')
			return
		}
		if (util.isEmpty(that.data.forecastVisitingTime)) {
			util.showToast('请求错误,来访日期不可为空!')
			return
		}
		if (util.isEmpty(that.data.forecastDepartureTime)) {
			util.showToast('请求错误,出园日期不可为空!')
			return
		}
		if (util.isEmpty(that.data.districtno)) {
			util.showToast('请求错误,受访区域不可为空!')
			return
		}
		if (util.isEmpty(that.data.visitorCompany)) {
			util.showToast('请求错误,访客单位不可为空!')
			return
		}
		if (util.isEmpty(that.data.visitingMatters)) {
			util.showToast('请求错误,来访事宜不可为空!')
			return
		}
		
		/**
		 * 2、创建请求信息体
		 */
		//显示加载提示
		wx.showLoading({
			title: '加载中...',
		})
		
		let submitData = {
			reservationno: that.data.reservationno,
			deptno: that.data.deptno,
			deptname: that.data.deptname,
			employeenoReception: that.data.employeenoReception,
			employeenameReception: that.data.employeenameReception,
			employeenoPhone: that.data.employeenoPhone,
			forecastVisitingTime: that.data.forecastVisitingTime,
			forecastDepartureTime: that.data.forecastDepartureTime,
			districtno: that.data.districtno,
			districtName: that.data.districtName,
			visitorCompany: that.data.visitorCompany,
			visitingMatters: that.data.visitingMatters,
		}
		
		//获取visitors中的信息
		let visitors = that.data.visitors
		let reservationList = []
		
		for (let i = 0; i < visitors.length; i++) {
			let reservation_single = {}
			reservation_single.visitor = visitors[i].mVisitor
			reservation_single.idcardno = visitors[i].mIdcardno
			reservation_single.carryItems = visitors[i].mCarryitems
			reservation_single.visitorPosition = visitors[i].mVisitorposition
			reservation_single.phone = visitors[i].mPhone
			//根据visitor.mPhotoUrl获取其对应的photoBase64
			let photoBase64 = null
			if (!util.isEmpty(visitors[i].mPhotoUrl)) {
				photoBase64 = that.getPhotoBase64(visitors[i].mPhotoUrl)
			}
			reservation_single.photoBase64 = photoBase64
			
			reservationList.push(reservation_single)
		}
		submitData.reservationList = reservationList
		
		/**
		 * 3、提交submitData中的信息。
		 */
		let url = app.globalData.baseUrl + "/reservation/saveReservationPrimary"
		networkUtilV2.httpPost(url, submitData).then((res) => {
			/**
			 * 若提交预约信息成功
			 */
			console.info("提交预约信息成功!", res)
			util.showToast("提交预约信息成功!")
			//返回到列表页面
			let goBack = () => {
				wx.navigateBack({
					delta: 1
				})
			}
			setTimeout(goBack, 1000)
		}).catch((res) => {
			/**
			 * 若提交信息失败，打印失败信息。
			 */
			console.error("提交预约信息时，发生错误!", res)
			util.showToast(res.message)
		})
	},
	
	/**
	 * 请求频率限制》分析 "目标方法" 的调用频率是否低于 "限制频率"。
	 */
	isBeyondLimitInterval: function () {
		let that = this
		let millisecond_current = new Date().getTime()
		let lastInvokeMillisecond = that.data.lastInvokeMillisecond
		
		//若lastInvokeMillisecond为null
		if (lastInvokeMillisecond == null) {
			that.setData({
				lastInvokeMillisecond: millisecond_current
			})
			return true;
		}
		
		/**
		 * 若lastInvokeMillisecond不为null，分析本次请求是否低于“限制频率”。
		 */
			//限制时间间隔
		let interval_given = 1000
		let interval_actual = millisecond_current - lastInvokeMillisecond
		if (interval_actual >= interval_given) {
			that.setData({
				lastInvokeMillisecond: millisecond_current
			})
			return true
		} else {
			that.setData({
				lastInvokeMillisecond: millisecond_current
			})
			return false
		}
	},
	
	/**
	 * 打开"来访事宜"textarea文本框。
	 */
	open_visitMatter: function () {
		this.setData({
			visitMatterStatus: true
		})
	},
	
	/**
	 * 关闭"来访事宜"textarea文本框。
	 */
	close_visitMatter: function () {
		this.setData({
			visitMatterStatus: false
		})
	},
	
	/**
	 * catchEvent,捕获事件。
	 */
	catchEvent: function (event) {
		//console.log("reservation.add.catchEvent().event", event)
	},
	
	
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {
	
	},
	
	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
	
	},
	
	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {
	
	},
	
	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
	
	},
	
	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {
	
	},
	
	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {
	
	},
	
	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {
	
	}
})